import router from 'umi/router';
import settings from '@/settings';

import { formatterData } from '@/components/SiderMenu';
import Dialog from '@/components/Dialog';
import { loguser, logout } from '@/services/login';

export default {
  namespace: 'app',
  state: {
    user: {},
    menu: [],
    pathname: '',
    fixed: true,
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    }
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        dispatch({
          type: 'updateState',
          payload: {
            pathname: location.pathname,
          },
        });

        Dialog.destroyAll();
      });
    },
    setup({ dispatch, history }) {

    },
  },
  effects: {
    *menu({ payload }, { put, select }) {
      const { routes } = payload;
      const { authorities = [] } = yield select(_ => _.app.user || {});

      const menu = formatterData(routes, authorities);

      yield put({
        type: 'updateState',
        payload: {
          menu,
        },
      });
    },
    *fetchCurrent({ payload }, { call, put }) {
      const { data } = yield call(loguser, payload);
      yield put({
        type: 'updateState',
        payload: {
          user: data,
        },
      });
    },
    *logout(_, { call, put }) {
      const { code } = yield call(logout);
      if (code === settings.code) {
        yield put({
          type: 'updateState',
          payload: {
            user: {},
          },
        });
        router.push('/login');
      }
    },
  },
};
